<template>
  <div class="content">
    <div ref="chartContainer" class="chart-container"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts";
import jiangxi from "@/assets/jiangxi.json";
const mapData: any = jiangxi;
const chartContainer = ref<HTMLElement | null>(null);
let chart: echarts.ECharts | null = null;

onMounted(() => {
  chart = echarts.init(chartContainer.value!);
  initChart();
  addHoverEventListener();
});

onBeforeUnmount(() => {
  if (chart) {
    chart.dispose();
    chart = null;
  }
});

function initChart() {
  echarts.registerMap("jiangxi", mapData);

  const option: echarts.EChartsOption = {
    backgroundColor: "#0e2152",
    title: {
      text: "江西省地图",
      left: "center",
      textStyle: {
        color: "#fff",
        fontSize: 28,
      },
    },
    tooltip: {
      trigger: "item",
      formatter: (params: any) => {
        // const { name, center, centroid } = params;
        return `地区名称: ${params.name}<br/>ID: ${params.dataIndex}`;
      },
    },
    series: [
      {
        type: "map",
        map: "jiangxi",
        itemStyle: {
          //   emphasis: {
          //     areaColor: "#fff", // 修改为黄色
          //   },
        },
        roam: true,
        emphasis: {
          label: {
            show: true,
          },
        },
        label: {
          show: true,
        },
        data: [],
      },
    ],
  };

  if (chart) {
    chart.setOption(option);
  }
}

function addHoverEventListener() {
  if (chart) {
    chart.on("click", (params: any) => {
      if (params.name) {
        console.log(params);
      }
    });
  }
}
</script>

<style scoped>
.content {
  background-color: #0e2152;
  height: 100%;
}

.chart-container {
  width: 100%;
  height: 100vh;
}
</style>
